#include "junix.h"

/* simple grep */
/* like program */
/* use regex.h */

int main(int argc, char **argv)
{

     if(argc!=3)
          err_quit("Usage:%s file file",argv[0] );

     char buf[LINE_MAX];
     
     int epfd=epoll_create(2);
     if(epfd==-1)
          err_sys("epoll_create");

     struct epoll_event event;

     int fd=open(argv[1],O_RDONLY);
     if(fd==-1)
          err_sys("open");

     int fd2=open(argv[2],O_RDONLY);
     if(fd==-1)
          err_sys("open");
     
     event.data.fd=fd;
     event.events=EPOLLIN;
     if( epoll_ctl(epfd, EPOLL_CTL_ADD, fd, &event) == -1 )
          err_sys("epoll_ctl");


     event.data.fd=fd2;
     if( epoll_ctl(epfd, EPOLL_CTL_ADD, fd2, &event) == -1 )
          err_sys("epoll_ctl");

     struct epoll_event *event_vec = alloca( sizeof( struct epoll_event)*2 );

     int i,nr;
     ssize_t sz;

     while(1)
     {
          nr= epoll_wait(epfd,event_vec,2,-1);
          if(nr==-1)
               err_sys("epoll_wait");

          for(i=0;i<nr;i++)
          {
               if( (sz=read(event_vec[i].data.fd,buf,LINE_MAX))>0)
                    if( write(STDOUT_FILENO,buf,sz) != sz)
                         err_sys("write");

               if(sz<0)
                    err_sys("read");
          }
     }

     exit(0);
}

